package com.luyou.awt.menu;

import java.awt.*;
import java.awt.event.*;

public class SimpleMenu {

    private Frame frame = new Frame();

    private MenuBar mb = new MenuBar();
    Menu file = new Menu("文件");

    MenuItem newItem = new MenuItem("新建");
    MenuItem saveItem = new MenuItem("保存");
    //创建exitItem菜单项，指定使用"ctrl + x" 快捷键
    MenuItem exitItem = new MenuItem("退出", new MenuShortcut(KeyEvent.VK_X));

    Menu edit = new Menu("编辑");
    CheckboxMenuItem autoWarp = new CheckboxMenuItem("自动换行");
    MenuItem copyItem = new MenuItem("复制");
    MenuItem pasterItem = new MenuItem("粘贴");

    Menu format = new Menu("格式");
    //创建commentItem菜单 指定"ctrl + shift + /"快捷键
    MenuItem commentItem = new MenuItem("注释", new MenuShortcut(KeyEvent.VK_SLASH, true));
    MenuItem cancelItem = new MenuItem("取消注释");

    private TextArea ta = new TextArea(6, 40);

    private void init(){
        ActionListener menuListener = e ->{
            String cmd = e.getActionCommand();
            ta.append("单击”" + cmd+"”菜单"+ "\n");
            if(cmd.equals("退出")){
                System.exit(0);
            }
        };
        //为commentItem菜单添加事件监听
        commentItem.addActionListener(menuListener);
        exitItem.addActionListener(menuListener);

        //为file菜单项添加菜单项
        file.add(newItem);
        file.add(saveItem);
        file.add(exitItem);

        //为edit菜单添加菜单项
        edit.add(autoWarp);
        //使用addSeparator方法来添加菜单分隔线
        edit.addSeparator();
        edit.add(copyItem);
        edit.add(pasterItem);

        //为format菜单添加菜单项
        format.add(commentItem);
        format.add(cancelItem);

        //使用new MenuItem的方式添加菜单分隔线
        edit.add(new MenuItem("-"));
        edit.add(format);

        //将file、edit菜单添加到mb菜单中
        mb.add(file);
        mb.add(edit);

        //为窗口设置菜单条
        frame.setMenuBar(mb);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.add(ta);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new SimpleMenu().init();
    }

}
